#include "connectiondialog.h"
#include <QtGui>
#include <iostream>
#include <boost/thread.hpp>
#include <boost/bind.hpp>
#include <QDebug>
#include <client/dbclient.h>
using namespace mongo;
using namespace boost;
#include "preferences.h"
// config file like that
/*   ---------
 *   Connections
 *    --defaultConn  1
 *    --connectName1(defaultConn?)
 *      --hostname
 *      --port
 *      --username
 *      --password
 *    --connectName2
 *
 *
 */
ConnectionDialog::ConnectionDialog(QWidget* parent)
    :QDialog(parent)
{
    setupUi(this);
    defaultConnectName=tr("defaultConn");
    connectGroupName=tr("Connections");
    hostnameLineEdit->setText(tr("localhost"));
    portSpinBox->setValue(27017);

    connect(this,SIGNAL(accepted()),this,SLOT(connect2DataBase()));
    connect(connectionsComboBox,SIGNAL(currentIndexChanged(int)),this,SLOT(readSettings()));
    connect(saveConnectionSetting,SIGNAL(clicked()),this,SLOT(saveSetting()));
    connect(removeConnectionSetting,SIGNAL(clicked()),this,SLOT(removeSetting()));
    connect(clearPushButton,SIGNAL(clicked()),this,SLOT(clearCurrent()));
    connection=NULL;
    QSettings currentSetting(
                Preferences::instance()->getCompanyName(),
                Preferences::instance()->getAppName());
    currentSetting.beginGroup(connectGroupName);
    QStringList allConnects=currentSetting.childGroups();
    int defaultConnIndex=currentSetting.value(connectGroupName+tr("/")+defaultConnectName).toInt();
    connectionsComboBox->addItems(allConnects);
    connectionsComboBox->setCurrentIndex(defaultConnIndex);
    connectionProgressBar->setValue(0);
    readSettings();
}


void ConnectionDialog::readSettings()
{
    QSettings currentSetting(
                Preferences::instance()->getCompanyName(),
                Preferences::instance()->getAppName());
    QString connStr=connectionsComboBox->currentText();
    currentSetting.beginGroup(tr("Connections/")+connStr);
    hostnameLineEdit->setText(currentSetting.value("hostname").toString());
    portSpinBox->setValue(currentSetting.value("port").toInt());
    usernameLineEdit->setText(currentSetting.value("username").toString());
    passwordLineEdit->setText(currentSetting.value("password").toString());
    currentSetting.endGroup();

}

void ConnectionDialog::connect2DataBase()
{
    QSettings currentSetting(
                Preferences::instance()->getCompanyName(),
                Preferences::instance()->getAppName());
    currentSetting.setValue(connectGroupName+tr("/")+defaultConnectName,
                            connectionsComboBox->currentIndex());
    //disable some controls
    hostnameLineEdit->setEnabled(false);
    portSpinBox->setEnabled(false);
    usernameLineEdit->setEnabled(false);
    passwordLineEdit->setEnabled(false);
    this->buttonBox->button(QDialogButtonBox::Ok)->setText(tr("Cancel"));

    boost::thread connectThread(boost::bind(&ConnectionDialog::doConnect,this));
    connectThread.join();
}


void ConnectionDialog::saveSetting()
{
    QString curConnectStr=connectionsComboBox->currentText();
    if(connectionsComboBox->findText(curConnectStr)!=-1)
    {
        QMessageBox::warning(this,tr("Warning"),tr("duplicate connection name!"),
                             QMessageBox::Ok | QMessageBox::Cancel,
                            QMessageBox::Ok);
        return ;
    }
    QSettings currentSetting(
                Preferences::instance()->getCompanyName(),
                Preferences::instance()->getAppName());

    QString hostname=hostnameLineEdit->text();
    int port=portSpinBox->value();
    QString username=usernameLineEdit->text();
    QString password=passwordLineEdit->text();
    currentSetting.beginGroup(tr("Connections/")+connectionsComboBox->currentText());
    currentSetting.setValue("hostname",hostname);
    currentSetting.setValue("port",port);
    currentSetting.setValue("username",username);
    currentSetting.setValue("password",password);
    currentSetting.endGroup();
    connectionsComboBox->addItem(connectionsComboBox->currentText());
}


void ConnectionDialog::removeSetting()
{
    int selectedConnection=connectionsComboBox->currentIndex();
    connectionSettings.removeAt(selectedConnection);
    clearCurrent();
}


void ConnectionDialog::clearCurrent()
{
    hostnameLineEdit->clear();
    portSpinBox->setValue(0);
    usernameLineEdit->clear();
    passwordLineEdit->clear();
}

void ConnectionDialog::doConnect()
{
    try{
        //progress
        int max=connectionProgressBar->maximum();
        this->connectionProgressBar->setValue(max/3);
        boost::this_thread::sleep(boost::posix_time::seconds(1));
        QString hostname=hostnameLineEdit->text();
        int port=portSpinBox->value();
        QString hostAndPort=tr("%1:%2").arg(hostname).arg(port);
        this->connectionProgressBar->setValue(max*2/3);
        boost::this_thread::sleep(boost::posix_time::seconds(1));
        connection=new DBClientConnection;
        string errorMsg;
        bool isConnected=connection->connect(hostAndPort.toLocal8Bit(),errorMsg);
        this->connectionProgressBar->setValue(max);
        if(isConnected)
        {
            emit requestConnectParamater(connectionsComboBox->currentText(),connection);
        }
        else
        {
            //connect failed
//            QMessageBox::warning(this,tr("Waring"),tr("Connect Error:%1").arg(errorMsg.c_str()),
//                                 QMessageBox::Ok | QMessageBox::Cancel,
//                                QMessageBox::Ok);
        }
    }catch(DBException& e)
    {
        qDebug(e.what());
    }
}
